package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        /*
            1.获取原始文件名 getOriginalFilename();
            2.获取原始文件名后缀 substring();
            3.处理唯一文件名 UUID.randomUUID();
            4.处理日期格式 new SimpleDateFormat("/yyyy/MM/dd/");
            5.创建目录: d:/files/2025/03/12/
            6.保存文件: d:/files/2025/03/12/xxx.jpg
            7.返回响应;
         */
        //1.处理文件名
        String filename = file.getOriginalFilename(); //xxx.jpg
        String suffix = filename.substring(filename.lastIndexOf(".")); //.jpg
        filename = UUID.randomUUID() + suffix; //d248f2e2-1387-48ba-b26f-5a6a4846de6e.jpg

        //2.处理路径并创建目录
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date()); // /2025/03/11/

        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        //3.保存文件: d:/files/2025/03/11/d248f2e2-1387-48ba-b26f-5a6a4846de6e.jpg
        String filePath = dirPath + datePath + filename;
        file.transferTo(new File(filePath));

        //4.返回响应
        return JsonResult.ok(datePath + filename);
    }
}
